package com.slipper.system.role.controller;

import com.slipper.constants.Constants;
import com.slipper.util.ResultUtil;
import com.slipper.util.Tool;
import com.slipper.system.employee.bo.EmployeeBO;
import com.slipper.system.role.bo.RoleBO;
import com.slipper.system.role.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 角色信息表
 */
@RestController
@RequestMapping("/system/role")
public class RoleController {
    @Resource
    private RoleService roleService;

    @PostMapping("/queryList")
    public String queryList(@RequestBody RoleBO bo) {
        bo.setAdmin(Constants.NO);
        if (!Constants.getCurrentUser().isSuperAdmin()) {
            bo.setOnlyCreateId(Constants.getCurrentUser().getEmployeeId());
        }
        return ResultUtil.successResult(roleService.queryList(bo));
    }
    
    @PostMapping("/queryPage")
    public String queryPage(@RequestBody RoleBO bo) {
        bo.setAdmin(Constants.NO);
        if (!Constants.getCurrentUser().isSuperAdmin()) {
            bo.setOnlyCreateId(Constants.getCurrentUser().getEmployeeId());
        }
        return ResultUtil.successResult(roleService.queryPage(bo));
    }

    @PostMapping("/save")
    public String save(@RequestBody RoleBO bo) {
        EmployeeBO employee = Constants.getCurrentUser().getEmployee();
        if (!Constants.getCurrentUser().isSuperAdmin() && bo.getId() != null ) {
            RoleBO role = this.roleService.queryBy(bo);
            if (role.getCreateId() != null && !role.getCreateId().equals(employee.getId())) {
                return ResultUtil.failureResult("此角色不由您创建，不允许修改！");
            }
        }

        bo.setCreateId(employee.getId());
        return ResultUtil.saveResult(roleService.save(bo));
    }

    @PostMapping("/queryBy")
    public String queryBy(@RequestBody RoleBO bo) {
        return ResultUtil.successResult(roleService.queryBy(bo));
    }

    @PostMapping("/delete")
    public String delete(@RequestBody RoleBO bo) {
        if (!Tool.isBlank(bo.getId())) {
            if (this.roleService.isUse(bo.getId())) {
                return ResultUtil.failureResult("此角色已经使用，不允许删除！");
            }
        }

        if (bo.getIds() != null) {
            for (String id : bo.getIds()) {
                if (this.roleService.isUse(id)) {
                    return ResultUtil.failureResult("此角色已经使用，不允许删除！");
                }
            }
        }

        return ResultUtil.deleteResult(roleService.delete(bo));
    }

    @PostMapping("/savePower")
    public String savePower(@RequestBody RoleBO bo) {
        return ResultUtil.saveResult(this.roleService.savePower(bo));
    }
}
